package com.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.utils.SinoDetect;

public class DdmapProcessor extends Processor {

	@Override
	public String getContentByCon(String entranceUrl, String cutStartString,
			String cutEndString) {
		StringBuffer sb = new StringBuffer();
		DataInputStream dis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		try {
			URL url = new URL(entranceUrl);
			//得到charset
			String charset = SinoDetect.getInstance().getCharset(url);
			HttpURLConnection uc = (HttpURLConnection) url.openConnection();
			uc.connect();
			int code = uc.getResponseCode();
			if (code != 200)
				return sb.toString();
			dis = new DataInputStream(uc.getInputStream());
			isr = new InputStreamReader(dis, charset);
			br = new BufferedReader(isr);
			String line = null;
			while ((line = br.readLine()) != null) {
				sb.append(line.trim());
				line = null;
			}
		} catch (MalformedURLException e) {
			System.out.println("getContent异常 1 : " + e.toString());
		} catch (IOException e) {
			System.out.println("getContent异常 2 : " + e.toString());
		} finally {
			if (br != null)
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (isr != null)
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (dis != null)
				try {
					dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

		String contentString = sb.substring(sb.indexOf(cutStartString), sb.indexOf(cutEndString));
		return contentString;
	}

	@Override
	public String getValueByCon(String content, String regex, String index) {
		String result = "";
		int indexInTab = Integer.parseInt(index);
		Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(content);
		int calc = 1;
		while (m.find()) {
			//目前所有的poi的元数据都包含在content中
			if(calc == indexInTab){
				result = m.group(m.groupCount());
				break;
			}
			calc++;
		}
		
		return result.trim();
	}

	public static void main(String[] args) {
		
	}

}
